package com.tepth.remote.control.delegate;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;

import com.blankj.utilcode.util.IntentUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.tepth.remote.control.R;
import com.tepth.remote.control.base.config.SpKey;
import com.tepth.remote.control.delegate.launcher.LauncherContract;
import com.tepth.remote.control.service.job.ControlCheckJob;
import com.tepth.remote.core.app.Control;
import com.tepth.remote.core.delegates.BaseControlDelegate;
import com.tepth.remote.core.utils.storage.ControlPreference;
import com.tepth.remote.ui.alert.DialogLoader;
import com.tepth.remote.ui.alert.IDialogClickListener;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/**
 * Description:
 *
 * @author Hequn.Lee
 * @date 2018/11/7
 */
@RuntimePermissions
public abstract class BasePermissionCheckerDelegate extends BaseControlDelegate {

    private LauncherContract.NeedPermissionCallback mCallback = null;

    @NeedsPermission(Manifest.permission.ACCESS_FINE_LOCATION)
    void startLocation() {
        startBootWithCode();
    }

    @NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void writeStorage() {
    }

    @NeedsPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
    void readStorage() {
        writeStorageWithCode();
    }

    @NeedsPermission(Manifest.permission.READ_PHONE_STATE)
    void readState() {
        if (mCallback != null) {
            @SuppressLint("MissingPermission") final String imei = PhoneUtils.getIMEI();
            mCallback.onNeedPermissionSuccess(imei);
        }
        startLocationWithCode();
    }

    @NeedsPermission(Manifest.permission.CAMERA)
    void startCamera() {
    }

    @NeedsPermission(Manifest.permission.RECEIVE_BOOT_COMPLETED)
    void startBoot() {
        startWakeLockWithCode();
    }

    @NeedsPermission(Manifest.permission.WAKE_LOCK)
    void startWakeLock() {
    }

    /**
     * 调起动态GPS权限授权
     */
    public void startLocationWithCode() {
        BasePermissionCheckerDelegatePermissionsDispatcher.startLocationWithPermissionCheck(this);
    }

    /**
     * 调起动态写入SD卡权限授权
     */
    public void writeStorageWithCode() {
        BasePermissionCheckerDelegatePermissionsDispatcher.writeStorageWithPermissionCheck(this);
    }

    /**
     * 调起动态读取SD卡权限授权
     */
    public void readStorageWithCode() {
        BasePermissionCheckerDelegatePermissionsDispatcher.readStorageWithPermissionCheck(this);
    }

    public void readStateWithCode(LauncherContract.NeedPermissionCallback callback) {
        if (callback != null) {
            mCallback = callback;
        }
        BasePermissionCheckerDelegatePermissionsDispatcher.readStateWithPermissionCheck(this);
    }

    /**
     * 动态调起相机权限
     */
    public void startCameraWithCode() {
        BasePermissionCheckerDelegatePermissionsDispatcher.startCameraWithPermissionCheck(this);
    }

    public void startBootWithCode() {
        BasePermissionCheckerDelegatePermissionsDispatcher.startBootWithPermissionCheck(this);
    }

    public void startWakeLockWithCode() {
        BasePermissionCheckerDelegatePermissionsDispatcher.startWakeLockWithPermissionCheck(this);
    }

    @OnPermissionDenied(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void onWriteStorageDenied() {
        final DialogLoader dialogLoader = new DialogLoader(getProxyActivity());
        dialogLoader.showWarning("提示",
                "禁止授权写入SD卡权限将影响本软件正常使用，请允许授权", new IDialogClickListener() {
                    @Override
                    public void onClick() {
                        writeStorageWithCode();
                        dialogLoader.clearDialog();
                    }
                });
    }

    @OnNeverAskAgain(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void onWriteStorageNever() {
        final DialogLoader dialogLoader = new DialogLoader(getProxyActivity());
        dialogLoader.showWarning("提示",
                "禁止授权写入SD卡权限将影响本软件正常使用，请允许授权", new IDialogClickListener() {
                    @Override
                    public void onClick() {
                        writeStorageWithCode();
                        dialogLoader.clearDialog();
                    }
                });
    }

    @OnPermissionDenied(Manifest.permission.READ_EXTERNAL_STORAGE)
    void onReadStorageDenied() {
        final DialogLoader dialogLoader = new DialogLoader(getProxyActivity());
        dialogLoader.showWarning("提示",
                "禁止授权读取SD卡权限将影响本软件正常使用，请允许授权", new IDialogClickListener() {
                    @Override
                    public void onClick() {
                        readStorageWithCode();
                        dialogLoader.clearDialog();
                    }
                });
    }

    @OnNeverAskAgain(Manifest.permission.READ_EXTERNAL_STORAGE)
    void onReadStorageNever() {
        final DialogLoader dialogLoader = new DialogLoader(getProxyActivity());
        dialogLoader.showWarning("提示",
                "禁止授权读取SD卡权限将影响本软件正常使用，请允许授权", new IDialogClickListener() {
                    @Override
                    public void onClick() {
                        readStorageWithCode();
                        dialogLoader.clearDialog();
                    }
                });
    }

    @OnPermissionDenied(Manifest.permission.ACCESS_FINE_LOCATION)
    void onLocationDenied() {
        final DialogLoader dialogLoader = new DialogLoader(getProxyActivity());
        dialogLoader.showWarning("提示",
                "禁止授权位置权限将影响本软件正常使用，请允许授权", new IDialogClickListener() {
                    @Override
                    public void onClick() {
                        startLocationWithCode();
                        dialogLoader.clearDialog();
                    }
                });
    }

    @OnNeverAskAgain(Manifest.permission.ACCESS_FINE_LOCATION)
    void onLocationNever() {
        final DialogLoader dialogLoader = new DialogLoader(getProxyActivity());
        dialogLoader.showWarning("提示",
                "禁止授权相机权限将影响本软件正常使用，请允许授权", new IDialogClickListener() {
                    @Override
                    public void onClick() {
                        startCameraWithCode();
                        dialogLoader.clearDialog();
                    }
                });
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    void onCameraDenied() {
        final DialogLoader dialogLoader = new DialogLoader(getProxyActivity());
        dialogLoader.showWarning("提示",
                "禁止授权相机权限将影响本软件正常使用，请允许授权", new IDialogClickListener() {
                    @Override
                    public void onClick() {
                        startCameraWithCode();
                        dialogLoader.clearDialog();
                    }
                });
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    void onCameraNever() {
        final DialogLoader dialogLoader = new DialogLoader(getProxyActivity());
        dialogLoader.showWarning("提示",
                "禁止授权位置权限将影响本软件正常使用，请允许授权", new IDialogClickListener() {
                    @Override
                    public void onClick() {
                        startLocationWithCode();
                        dialogLoader.clearDialog();
                    }
                });
    }

    @OnPermissionDenied(Manifest.permission.READ_PHONE_STATE)
    void onReadStateDenied() {
        if (mCallback != null) {
            mCallback.onNeedPermissionFailed();
        }
    }

    @OnNeverAskAgain(Manifest.permission.READ_PHONE_STATE)
    void onReadStateNever() {
        if (mCallback != null) {
            mCallback.onNeedPermissionFailed();
        }
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        BasePermissionCheckerDelegatePermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @SuppressLint("BatteryLife")
    @RequiresApi(api = Build.VERSION_CODES.M)
    protected void checkBatteryPermission() {
        final PowerManager manager = (PowerManager) Control.getApplicationContext().getSystemService(Context.POWER_SERVICE);
        if (!manager.isIgnoringBatteryOptimizations(ControlCheckJob.CONTROL_SERVICE_NAME)) {
            final Intent intent = new Intent();
            intent.setAction(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + Control.getApplicationContext().getPackageName()));
            if (IntentUtils.isIntentAvailable(intent)) {
//                new AlertDialog.Builder(getProxyActivity())
//                        .setCancelable(false)
//                        .setTitle("需要忽略电池优化")
//                        .setMessage(getString(R.string.app_name) + "的持续运行需要将 " + getString(R.string.app_name) + " 加入到电池优化的忽略名单。\n\n" +
//                                "请点击『确定』，在弹出的『忽略电池优化』对话框中，选择『是』。")
//                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                            }
//                        }).show();
                startActivity(intent);
            }
        }
    }

    protected void checkBootComplete() {
        if (!ControlPreference.getPreferenceBoolean(SpKey.KEY_CHECK_BOOT_COMPLETE)) {
            //华为 自启管理
            final Intent intent = new Intent();
            intent.setAction("huawei.intent.action.HSM_BOOTAPP_MANAGER");
            if (IntentUtils.isIntentAvailable(intent)) {
                new AlertDialog.Builder(getProxyActivity())
                        .setCancelable(false)
                        .setTitle("需要自动启动权限")
                        .setMessage(getString(R.string.app_name) + "的持续运行需要允许 " + getString(R.string.app_name) + " 的自动启动。\n\n" +
                                "请点击『确定』，在弹出的『自启管理』中，将 " + getString(R.string.app_name) + " 对应的开关打开。")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startActivity(intent);
                                ControlPreference.addCustomAppProfile(SpKey.KEY_CHECK_BOOT_COMPLETE, true);
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                    checkBatteryPermission();
                                }
                            }
                        }).show();
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    checkBatteryPermission();
                }
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                checkBatteryPermission();
            }
        }
    }
}
